import { comboHolder, filterAuth } from '@/support/common';
import { PlusOutlined } from '@ant-design/icons';
import { Badge, Button, Card, message, Tag } from 'antd';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import PateoModalForm from '../../../components/common/PateoModalForm';
import PateoSearchForm from '../../../components/common/PateoSearchForm';
import PateoTable from '../../../components/common/PateoTable';
import styles from '../../../components/common/PateoTable/TableList.less';
import Ellipsis from '../../../components/Ellipsis';
import AccountTransfer from './accountTransfer';
import Detail from './detail';
import RoleTransfer from './roleTransfer';

const mapStateToProps = (state: any) => ({
  dataPermission: state.dataPermission,
  loading: state.loading.effects['dataPermission/postFetchPage'],
});
class DataPermission extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      visible: false,
      postUrl: '',
      formData: {},
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'dataPermission/postFetchPage',
      payload: { url: '/datapermission/page' },
    });
  }

  handleAdd = () => {
    this.setState({
      visible: true,
      postUrl: '/datapermission/add',
    });
  };

  handleEdit = (record: any) => {
    this.setState({
      formData: record,
      visible: true,
      postUrl: '/datapermission/edit',
    });
  };

  handleDelete = (sid: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'dataPermission/postData',
      payload: { url: '/datapermission/del', dataPermissionSid: sid },
      callback: (res: any) => {
        message.success('删除成功！');
        this.handleFlushPage();
      },
    });
  };

  handleFlushPage = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'dataPermission/postFetchPage',
      payload: { url: '/datapermission/page', ...formValues },
    });
  };

  openDetail = (sid: any) => {
    const {
      location: { pathname = '/' },
    } = this.props;
    if (!filterAuth('dataPermission_doConfigList', this.context.permissions, pathname)) {
      return;
    }
    this.detail.open(sid);
  };

  openRoleTransfer = (sid: any) => {
    const {
      location: { pathname = '/' },
    } = this.props;
    if (!filterAuth('dataPermission_doRoleList', this.context.permissions, pathname)) {
      return;
    }
    this.roleTransfer.open(sid);
  };

  openAccountTransfer = (sid: any) => {
    const {
      location: { pathname = '/' },
    } = this.props;
    if (!filterAuth('dataPermission_doAccountList', this.context.permissions, pathname)) {
      return;
    }
    this.accountTransfer.open(sid);
  };

  render() {
    const {
      dataPermission: {
        pageData: { list, pagination },
      },
      loading,
      location: { pathname = '/' },
    } = this.props;
    const { formValues, visible, postUrl, formData } = this.state;
    const columns = [
      {
        title: '序号',
        dataIndex: 'index',
        width: 60,
        render: (text: any, record: any, index: any) => {
          return index + 1 + (pagination.current - 1) * pagination.pageSize;
        },
      },
      {
        title: '权限名称',
        dataIndex: 'dataPermissionName',
      },
      {
        title: '权限描述',
        dataIndex: 'dataPermissionDesc',
        render: (text: any) => {
          return (
            <Ellipsis length={20} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '关联角色',
        dataIndex: 'countRole',
        render: (text: any, record: any) => {
          return Number(text) == 0 || !text ? (
            <a onClick={() => this.openRoleTransfer(record.sid)}>
              <Tag color="red">未关联</Tag>
            </a>
          ) : (
            <Badge size="small" count={Number(text)} offset={[-6, 0]}>
              <a onClick={() => this.openRoleTransfer(record.sid)}>
                <Tag color="green">已关联</Tag>
              </a>
            </Badge>
          );
        },
      },
      {
        title: '关联账号',
        dataIndex: 'countAccount',
        render: (text: any, record: any) => {
          return Number(text) == 0 || !text ? (
            <a onClick={() => this.openAccountTransfer(record.sid)}>
              <Tag color="red">未关联</Tag>
            </a>
          ) : (
            <Badge size="small" count={Number(text)} offset={[-6, 0]}>
              <a onClick={() => this.openAccountTransfer(record.sid)}>
                <Tag color="green">已关联</Tag>
              </a>
            </Badge>
          );
        },
      },
      {
        title: '权限明细',
        dataIndex: 'countItem',
        render: (text: any, record: any) => {
          return Number(text) == 0 || !text ? (
            <a onClick={() => this.openDetail(record.sid)}>
              <Tag color="red">未关联</Tag>
            </a>
          ) : (
            <Badge size="small" count={Number(text)} offset={[-6, 0]}>
              <a onClick={() => this.openDetail(record.sid)}>
                <Tag color="green">已关联</Tag>
              </a>
            </Badge>
          );
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 150,
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '编辑',
              key: 'edit',
              auth: 'dataPermission_doEdit',
              onConfirm: () => this.handleEdit(record),
            },
            {
              title: '删除',
              key: 'delete',
              auth: 'dataPermission_doDel',
              Popconfirm: true,
              message: '是否确认删除？',
              onConfirm: () => this.handleDelete(record.sid),
            },
          ];
          return <PateoAuthButtons btns={btns} max={1} pathname={pathname} />;
        },
      },
    ];
    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const tableProps = {
      columns,
      dataSource: list,
      loading,
      rowKey: (record: any) => record.sid,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
    };
    const searchItems = [
      {
        type: 'input',
        title: '权限名称',
        key: 'dataPermissionName',
      },
    ];
    const formItems = [
      {
        type: 'input',
        title: '权限名称',
        key: 'dataPermissionName',
        rules: [{ required: true, message: comboHolder('权限名称'), whitespace: true }],
        maxLength: 20,
      },
      {
        type: 'textArea',
        title: '权限描述',
        key: 'dataPermissionDesc',
        rules: [{ required: true, message: comboHolder('权限描述'), whitespace: true }],
        maxLength: 50,
      },
    ];
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            searchItems={searchItems}
            fetchParams={{ type: 'dataPermission/postFetchPage', url: '/datapermission/page' }}
            saveFormValues={(val: any) =>
              this.setState({ formValues: Object.assign(formValues, val) })
            }
            handleFormReset={() => this.setState({ formValues: {} })}
          />
        </Card>
        <Card className={styles.standardTable}>
          {filterAuth('dataPermission_doAdd', this.context.permissions, pathname) ? (
            <div className="my_newItem">
              <Button
                size="small"
                icon={<PlusOutlined />}
                type="primary"
                onClick={() => this.handleAdd()}
              >
                新增
              </Button>
            </div>
          ) : null}
          <PateoTable
            extraHandle={true}
            tableProps={tableProps}
            fetchParams={{ type: 'dataPermission/postFetchPage', url: '/datapermission/page' }}
            formValues={formValues}
          />
        </Card>
        <PateoModalForm
          style={{ top: '10%' }}
          formItems={formItems}
          changeVisible={() => this.setState({ formData: {}, visible: false, postUrl: '' })}
          formData={formData}
          visible={visible}
          postUrl={postUrl}
          handleCallback={this.handleFlushPage}
          title={['新增数据权限', '编辑数据权限']}
          messageInfo={['新增成功', '编辑成功']}
          buttonName={['保存', '取消']}
        />
        <Detail
          onRef={(val: any) => (this.detail = val)}
          handleFlushPage={this.handleFlushPage}
          pathname={pathname}
        />
        <RoleTransfer
          onRef={(val: any) => (this.roleTransfer = val)}
          handleFlushPage={this.handleFlushPage}
          pathname={pathname}
        />
        <AccountTransfer
          onRef={(val: any) => (this.accountTransfer = val)}
          handleFlushPage={this.handleFlushPage}
          pathname={pathname}
        />
      </div>
    );
  }
}
export default connect(mapStateToProps)(DataPermission);
